const baseVer = wx.getSystemInfoSync().SDKVersion
const sysInfo = wx.getSystemInfoSync()

function compareVersion(v1, v2) {
  v1 = v1.split('.')
  v2 = v2.split('.')
  const len = Math.max(v1.length, v2.length)

  while (v1.length < len) {
    v1.push('0')
  }
  while (v2.length < len) {
    v2.push('0')
  }

  for (let i = 0; i < len; i++) {
    const num1 = parseInt(v1[i])
    const num2 = parseInt(v2[i])

    if (num1 > num2) {
      return 1
    } else if (num1 < num2) {
      return -1
    }
  }

  return 0
}

/**
 * 是否可跳转视频号
 */
function validateMiniVideoApi() {
    let rst = compareVersion(baseVer, '2.19.2')
    return rst >= 0
}

function validateOnlyBleAuth(callback) {
  //检查系统权限
  const sysSetting = getSysSetting(baseVer)
  console.log("获取系统权限-->", sysSetting)
  const appAuthSetting = getAppAuthSetting(baseVer)
  console.log("获取微信权限-->", appAuthSetting,sysInfo,  getApp().globalData.miniAuthSetting)
  if (sysSetting != null) {
    if (sysInfo.platform == 'ios' && appAuthSetting.bluetoothAuthorized != 'authorized') {
      return 'wx_ble'
    }
    if (!sysSetting.bluetoothEnabled) {     
      return 'sys_ble_' + sysInfo.platform            
    }       
  }

  //检查微信授权情况
  if (appAuthSetting != null) {   
    if (sysInfo.platform == 'ios' && appAuthSetting.bluetoothAuthorized != 'authorized') {
      return 'wx_ble'
    }
  }

  //检查微信小程序授权情况
  getMiniSetting(baseVer)
  let miniAuthSetting = getApp().globalData.miniAuthSetting
  console.log("小程序授权情况：", miniAuthSetting)
  if (miniAuthSetting != null && miniAuthSetting["scope.bluetooth"] === false) {
    return 'mini_ble'
  }else if (miniAuthSetting != null && miniAuthSetting["scope.bluetooth"] != true) {
     //不存在授权项，弹出授权
     wx.authorize({
        scope: 'scope.bluetooth',
        success () {
          if(callback) {
            callback('mini_ble')
          }
        }
     })
     return 'mini_ble'
  }

  return 'pass'

}
function validateOnlyLocationAuth() {
  const sysSetting = getSysSetting(baseVer)
  const appAuthSetting = getAppAuthSetting(baseVer)

  if (sysSetting && !sysSetting.locationEnabled) {
    return 'sys_location'
  }
  if (appAuthSetting && appAuthSetting.locationAuthorized != 'authorized') {
    //微信不能使用定位权限
    return 'wx_location'
  }   
 
  return 'pass'
}

function validateBleAuth() {
  //检查系统权限
  const sysSetting = getSysSetting(baseVer)
  console.log("获取系统权限-->", sysSetting)
  const appAuthSetting = getAppAuthSetting(baseVer)
  
  //检查微信小程序授权情况
  getMiniSetting(baseVer)
  let miniAuthSetting = getApp().globalData.miniAuthSetting
  console.log("小程序授权情况：", miniAuthSetting)
  if (miniAuthSetting != null && miniAuthSetting["scope.bluetooth"] === false) {
    return 'mini_ble'
  }else if (miniAuthSetting != null && miniAuthSetting["scope.bluetooth"] != true) {
    //不存在授权项，弹出授权
    wx.authorize({
     scope: 'scope.bluetooth',
     success () {
     }
    })
    return 'mini_ble'
  }

  console.log("获取微信权限-->", appAuthSetting,sysInfo,  getApp().globalData.miniAuthSetting)
  if (sysSetting != null) {
    if (sysInfo.platform == 'ios' && appAuthSetting.bluetoothAuthorized != 'authorized') {
      return 'wx_ble'
    }
    if (!sysSetting.bluetoothEnabled) {     
      return 'sys_ble_' + sysInfo.platform            
    }   
  }

  //检查微信授权情况
  if (appAuthSetting != null) {
    if (sysInfo.platform == 'ios' && appAuthSetting.bluetoothAuthorized != 'authorized') {
      return 'wx_ble'
    }         
  }
  
  if (sysSetting && !sysSetting.locationEnabled) {
    return 'sys_location'
  }
  if (appAuthSetting && appAuthSetting.locationAuthorized != 'authorized') {
    //微信不能使用定位权限
    return 'wx_location'
  }   
  
  return 'pass'
}
/**
 * 获取系统配置信息
 * @param {*} baseVer 
 */
function getSysSetting(bVer) {
  if(!bVer) {
    bVer = baseVer
  }
  console.log("基础库版本:", bVer)
  let verRst = compareVersion(bVer, '2.20.1')
  if (verRst >= 0) {
    return wx.getSystemSetting()
  }
  return null
}
/**
 * 获取app授权配置
 * @param {*} baseVer 
 */
function getAppAuthSetting(baseVer) {
  let verRst = compareVersion(baseVer, '2.20.1')
  if (verRst >= 0) {
    return wx.getAppAuthorizeSetting()
  }
  return null
}
/**
 * 获取小程序的授权配置
 */
function getMiniSetting(bVer) {
  if (!bVer) {
    bVer = baseVer
  }
  let verRst = compareVersion(bVer, '1.2.0')
  if (verRst >= 0) {
    wx.getSetting({
      success(res) {
        console.log("小程序授权信息:", res, res.authSetting["scope.bluetooth"])
        getApp().globalData.miniAuthSetting = res.authSetting
      }
    })
  }
}

function toSetMiniAuthSetting() { // mark: 去设置小程序授权配置
  wx.showModal({
    title: '提示',
    content: '连接设备需打开小程序蓝牙权限,点击"确定"去打开',
    success(res) {
      if (res.confirm) {
        wx.openSetting({
          success(res) {
            console.log(res.authSetting)
            getApp().globalData.miniAuthSetting = res.authSetting
          }
        })
      } else if (res.cancel) {
        console.log('用户点击取消授权')
      }
    }
  })
}


module.exports.compareVersion = compareVersion
module.exports.getMiniSetting = getMiniSetting
module.exports.validateBleAuth = validateBleAuth
module.exports.toSetMiniAuthSetting = toSetMiniAuthSetting
module.exports.getSysSetting = getSysSetting
module.exports.validateMiniVideoApi = validateMiniVideoApi
module.exports.validateOnlyBleAuth = validateOnlyBleAuth
module.exports.validateOnlyLocationAuth = validateOnlyLocationAuth